package net.fdukedom.epicurus.pm.actions;

import net.fdukedom.epicurus.pm.domain.entity.PrivateMessage;
import net.fdukedom.epicurus.pm.domain.util.PrivateMessageHelper;
import net.fdukedom.epicurus.presentation.actions.AbstractAction;
import net.fdukedom.epicurus.presentation.SessionData;
import net.fdukedom.epicurus.domain.entity.User;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Dmitry Y. Kochelaev
 */
public class ViewMessageAction extends AbstractAction {

    private PrivateMessageHelper privateMessageHelper = PrivateMessageHelper.getInstance();

    protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
        User user = SessionData.getInstance(request).getUser();
        int messageId;
        try {
            messageId = Integer.parseInt(request.getParameter("id"));
        } catch (NumberFormatException e) {
            return mapping.findForward("fail");
        }
        PrivateMessage message = privateMessageHelper.findByIdandUser(messageId, user);
        if (message == null) {
            return mapping.findForward("fail");
        }
        message.setIsRead(true);
        privateMessageHelper.savePrivateMessage(message);
        request.setAttribute("message", message);
        return mapping.findForward("success");
    }
}
